package com.common.tools.controller;

import com.common.convert.ConverterConfig;
import com.common.convert.ConverterRouter;
import com.common.tools.utils.MultipartFileUtils;
import org.jodconverter.core.DocumentConverter;
import org.jodconverter.core.office.OfficeException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.PostConstruct;
import java.io.File;
import java.io.IOException;

@RestController
@RequestMapping("convert")
public class ConvertController {

    @Autowired
    private DocumentConverter documentConverter;
    private ConverterRouter converterRouter;

    @Value("${converter.workDir}")
    private String workDir;

    @Autowired
    public ConvertController() {
        this.converterRouter = new ConverterRouter();
    }

    @PostConstruct
    public void init() {
        ConverterConfig.DOCUMENT_CONVERTER = documentConverter;
        ConverterConfig.OUT_DIR = workDir + File.separator + "out" + File.separator;
    }

    @PostMapping("office")
    public String office(@RequestParam("file") MultipartFile file, String outType) throws IOException, OfficeException {
        File tempFile = MultipartFileUtils.save(file, workDir);
        return converterRouter.convert(tempFile, outType);
    }

}
